package com.example.fanyi.api

import java.security.MessageDigest
import java.util.UUID

object YoudaoUtils {
    private const val APP_KEY = "61358e19277bfc8f"
    private const val APP_SECRET = "w87ms3VDFtQHy74HBJnyj41k7gggIVSJ"

    fun generateSalt(): String = UUID.randomUUID().toString()

    fun getCurrentTime(): String = (System.currentTimeMillis() / 1000).toString()

    fun generateSign(text: String, salt: String, curtime: String): String {
        // 计算input
        val input = if (text.length <= 20) text else text.substring(0, 10) + text.length + text.substring(text.length - 10)
        
        // 打印调试信息
        android.util.Log.d("YoudaoSign", "原始文本: $text")
        android.util.Log.d("YoudaoSign", "处理后的input: $input")
        
        // 拼接字符串 appKey+input+salt+curtime+appSecret
        val signStr = APP_KEY + input + salt + curtime + APP_SECRET
        android.util.Log.d("YoudaoSign", "签名字符串: $signStr")
        
        val sign = sha256(signStr)
        android.util.Log.d("YoudaoSign", "最终签名: $sign")
        return sign
    }

    private fun sha256(input: String): String {
        val md = MessageDigest.getInstance("SHA-256")
        val digest = md.digest(input.toByteArray())
        return digest.joinToString("") { "%02x".format(it) }
    }
} 